package com.meituan.sqt.client;

import com.meituan.sqt.request.BaseApiRequest;
import com.meituan.sqt.request.thirdpay.ThirdPayMockRequest;
import com.meituan.sqt.utils.EncryptUtil;
import com.meituan.sqt.utils.HttpClientUtil;
import com.meituan.sqt.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: chenzhenfeng@meituan.com
 * @date: 2020/10/29 6:58 下午
 * @description:
 */
public class SqtClient {
    private static final Logger log = LoggerFactory.getLogger(SqtClient.class);
    private static final String VERSION = "1.0";
    private static final String FORM_URLENCODED = "application/x-www-form-urlencoded";
    private static final String ACCEPT_JSON = "application/json";
    // 测试环境域名
    protected String host = "https://inf-openapi.apigw.test.meituan.com/api/sqt/openapi";
    protected String token;
    protected Long entId;
    protected String aesKey;

    public SqtClient(String token, Long entId, String aesKey) {
        this.token = token;
        this.entId = entId;
        this.aesKey = aesKey;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getAesKey() {
        return aesKey;
    }

    public void setAesKey(String aesKey) {
        this.aesKey = aesKey;
    }

    public String commonPostInvoke(String url, BaseApiRequest request) {
        request.setTs(System.currentTimeMillis()/1000);
        request.setEntId(this.entId);
        try {
            String rawContent = JsonUtil.object2Json(request, false);
            System.out.println(rawContent);
            String body = "token=" + getToken() + "&version=" + VERSION
                    + "&content=" + EncryptUtil.aesEncrypt(rawContent, getAesKey());
            String responseStr = HttpClientUtil.invokePost(url, body, FORM_URLENCODED, ACCEPT_JSON);
            return responseStr;
        } catch (Exception e) {
            log.error("HTTP调用失败, url:{}", url, e);
        }
        return null;
    }


    public String jsonPostInvoke(String url, String body) {
        try {
            return HttpClientUtil.invokePost(url, body, "application/json; charset=utf-8", "application/json");
        } catch (Exception e) {
            log.error("HTTP调用失败, url:{}", url, e);
        }
        return null;
    }

    // 用于第三方进行三方支付接入联调测试
    public String thirdPayMockTest(ThirdPayMockRequest req) {
        req.setMethod("trade.third.standard.mock");
        return this.commonPostInvoke(this.host + "/trade/standardThird/mock/test", req);
    }
}
